<template>
  <div class="app-portal-body">
    <div class="app-portal-menucontent" v-if="app">
      <forms
        ref="appForms"
        :app-id="app.group_id"
        :selected-id="defaultFid"
        @select="handleSelectForm"
      />
    </div>
    <div v-if="currentData" class="app-portal-content">
      <div class="app-portal-cnt-hd">
        <div class="flex items-center">
          <div class="app-portal-hd-icon" @click="refreshMain">
            <JIcon :icon="DFT_ICONS.refresh" class="reload-icon" />
            表
          </div>
          <div class="app-portal-title">{{ currentData.form_name }}</div>
          <div
            class="app-portal-mark"
            v-copy="currentData.form_code"
            style="cursor: pointer"
            v-tippy="{ arrow: true, placement: 'right' }"
            content="点击复制"
          >
            {{ currentData.form_code }}
          </div>
        </div>
        <div class="app-portal-tools">
          <JIcon
            :icon="DFT_FILL_ICONS.setting"
            class="app-portal-action first"
            v-tippy
            content="表单编辑"
            @click="handleFormShowEdit"
          />
          <el-badge :value="viewNum" :hidden="!currentData.views || currentData.views.length <= 0">
            <JIcon
              :icon="DFT_FILL_ICONS.formview"
              class="app-portal-action"
              v-tippy
              content="视图设置"
              @click="handleShowViews"
            />
          </el-badge>
          <el-badge
            :value="currentFormBtnNum"
            :hidden="!currentFormBtnNum || currentFormBtnNum <= 0"
          >
            <JIcon
              :icon="DFT_FILL_ICONS.switch"
              class="app-portal-action"
              v-tippy
              content="按钮配置"
              @click="handleFormShowSetting('action')"
            ></JIcon>
          </el-badge>
          <el-badge
            :value="currentFormSyncNum"
            :hidden="!currentFormSyncNum || currentFormSyncNum <= 0"
          >
            <JIcon
              :icon="DFT_FILL_ICONS.sync"
              class="app-portal-action"
              v-tippy
              content="智能同步"
              @click="handleFormShowSetting('sync')"
            />
          </el-badge>
          <JIcon
            :icon="DFT_FILL_ICONS.code"
            class="app-portal-action"
            v-tippy
            content="低码开发"
            @click="handleFormShowSetting('lowcode')"
          />
          <JIcon
            :icon="DFT_FILL_ICONS.formflow"
            class="app-portal-action"
            v-if="currentData.use_type === 'WORKFLOW'"
            v-tippy
            content="流程类表单"
            @click="handleShowFlowEditWin"
          ></JIcon
          ><!-- fa-share-alt -->
          <el-dropdown
            v-if="app"
            trigger="click"
            placement="bottom-start"
            size="small"
            @command="handleFormCommand"
          >
            <JIcon
              :icon="DFT_ICONS.more"
              class="app-portal-action last"
              v-tippy
              content="更多"
            />
            <template #dropdown>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="copy">
                  <JIcon :icon="DFT_ICONS.copy" class="el-icon-document-copy" />
                  复制
                </el-dropdown-item>
                <el-dropdown-item command="cache">
                  <JIcon :icon="DFT_ICONS.refresh" />
                  缓存
                </el-dropdown-item>
                <el-dropdown-item command="remove">
                  <JIcon :icon="DFT_ICONS.delete" />
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="app-portal-paneltab" style="width: 280px">
          <el-tabs v-model="panelTabActive">
            <el-tab-pane label="" name="datas">
              <template #label>
                <el-dropdown
                  trigger="click"
                  placement="bottom-start"
                  @command="handleChangeView"
                >
                  <span
                    >{{ currentFormViewLabel }}
                    <JIcon
                      :icon="DFT_ICONS.sortDown"
                      class="el-icon-arrow-down el-icon--right"
                    />
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu slot="dropdown">
                      <div style="max-height: 500px; overflow-y: auto">
                        <el-dropdown-item :command="-1">原始表单 </el-dropdown-item>
                        <el-dropdown-item :command="v.form_view_id" v-for="v in currentData.views"
                          >视图：{{ v.view_name }}
                        </el-dropdown-item>
                      </div>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-tab-pane>
            <!-- 概览显示数据统计：总数、已审核、未通过等数据，还显示表单低码的日志，如：同步日志、 -->
            <!--<el-tab-pane label="概览" name="overview"></el-tab-pane>-->
            <!--<el-tab-pane label="统计报表" name="chart"></el-tab-pane>-->
            <el-tab-pane :label="currentFormTemplateLabel" name="template"></el-tab-pane>
            <el-tab-pane :label="currentFormMsgtplLabel" name="msgtpl"></el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <div class="app-portal-cnt-bd">
        <template v-if="currentData">
          <datas
            v-if="panelTabActive === 'datas'"
            :form-id="currentData.form_id"
            :view-id="currentFormViewId"
          />
          <FormTemplate
            v-else-if="panelTabActive === 'template'"
            :form-id="currentData.form_id"
          />
          <FormMsgtpl
            v-else-if="panelTabActive === 'msgtpl'"
            :form-id="currentData.form_id"
            :form-info="currentData"
            class="pt-2"
          />
        </template>
      </div>
    </div>
    <div v-else-if="app" class="app-portal-content app-portal-explain">
      <h2 v-text="app.group_name"></h2>
      <p v-text="app.group_desc"></p>
    </div>
    <div v-else class="app-portal-content app-portal-explain">
      <h2>应用管理</h2>
      <p>应用管理，以应用为中心，请左侧先选择具体应用！</p>
    </div>

    <!-- form begin -->
    <!--    <el-dialog
      :title="formWinName"
      v-model="showFormCreate"
      :fullscreen="true"
      class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true">
      <form-create
        v-if="showFormCreate"
        use-type="WEB"
        :formInfo.sync="formInfo"
        :show.sync="showFormCreate" :is-show-form="true"
        @close="handleCloseFormWin"
      />
    </el-dialog>-->

    <!--    <el-dialog
      :title="viewsWinName"
      v-model="showViewWin"
      :fullscreen="true"
      class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true">
      <form-views
        v-if="showViewWin && formInfo"
        :form-id.sync="formInfo.form_id"
        :show.sync="showViewWin"
        @close="handleCloseViewWin"
      />
    </el-dialog>-->

    <el-dialog
      :title="copyWinName"
      v-model="isShowCopy"
      width="400px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form label-width="90px">
        <el-form-item label="新表单名称">
          <el-input v-model="copyForm.form_name"></el-input>
        </el-form-item>
        <el-form-item label="新表单编码">
          <el-input v-model="copyForm.form_code"></el-input>
        </el-form-item>
      </el-form>
      <div class="text-center">
        <el-button type="primary" @click="formCopy()"> 提交</el-button>
        <el-button @click="handleCloseCopyWin()"> 取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="flowWinName"
      v-model="showFlowCreate"
      :fullscreen="true"
      custom-class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <flow-create
        v-if="showFlowCreate"
        :show.sync="showFlowCreate"
        :flow-id="flowForm && flowForm.flow_id"
        :rel-form-id="flowForm && flowForm.form_id"
        :is-view="isView"
        @close="handleCloseFlowWin"
      />
    </el-dialog>

    <!--    <el-dialog
      :title="settingWinName"
      v-model="showSettingCreate"
      :fullscreen="true"
      class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true">
      <form-setting
        v-if="showSettingCreate"
        :show.sync="showSettingCreate"
        :step-active="settingStepActive"
        :form-id="formInfo && formInfo.form_id"
        :is-view="isView"
        @close="handleCloseSettingWin"
      />
    </el-dialog>-->
    <!-- form end -->
  </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue';
import _ from 'lodash';
import forms from './modules/app-forms.vue';
// import formCustom from '../pages/form-custom.vue';
// import formLink from '../pages/form-link.vue';
import FormTemplate from '@/views/basic/form/form-template.vue';
import FormMsgtpl from '@/views/basic/form/form-msgtpl.vue';
import { useRouter } from 'vue-router';
import { DFT_FILL_ICONS, DFT_ICONS } from '@jzl/icons';
import { api } from '@jzl/api';
import { $jui } from '@jzl/utils';
import { $WinFormSetting, $WinFormViews } from '@jzl/comps-mg';
import { $WinFormCreate } from '@jzl/comps-mg/src/form/src/win-form-setting.js';

const emit = defineEmits(['select']);
const props = defineProps({
  app: Object
});

const router = useRouter();

const defaultFid = ref(null);
const currentData = ref(null);
const panelTabActive = ref('datas');

const currentFormViewId = ref(-1);
const currentFormViewLabel = ref('原始表单');

// form 修改/新增
const showFormCreate = ref(false);
const isView = ref(false);
const formWinName = ref('新增');

// form 复制
const formInfo = ref(null);
const isShowCopy = ref(false);
const copyForm = ref({});
const copyWinName = ref('');

const showViewWin = ref(false);
const viewsWinName = ref('');

const showActionWin = ref(false);
const actionWinName = ref('');

// form flow
const showFlowCreate = ref(false);
const flowWinName = ref('');
const modFlowId = ref(null);
const flowForm = ref(null);

// form setting/lowcode
const settingWinName = ref('高级设置');
const showSettingCreate = ref(false);
const settingStepActive = ref('2');

const init = () => {
  defaultFid.value = router.currentRoute.value.query.fid;
};

const emptyData = () => {
  currentData.value = null;
  currentFormViewId.value = -1;
};

const handleSelectForm = (data) => {
  currentData.value = data;
  const formId = _.get(data, 'form_id');

  if (formId) {
    router.push({
      name: 'portal-app-form',
      params: {
        appId: _.get(props.app, 'group_id')
      },
      query: {
        fid: formId
      },
      replace: true
    });
  }
};

const getFormInfo = async (formId) => {
  const form = await api.form.getFormById(formId);
  const views = await api.form.getFormViews(formId);

  if (form) form.views = views;

  return form;
};

const handleFormCommand = (cmd) => {
  if (cmd === 'info') {
    handleFormShowEdit();
  } else if (cmd === 'copy') {
    handleShowCopy();
  } else if (cmd === 'remove') {
    handleFormDelete();
  } else if (cmd === 'cache') {
    handleFormCacheClean();
  }
};

const handleFormDelete = () => {
  const it = currentData.value;
  if (!it || !it.form_id) return;

  $jui
    .confirm(`此操作将永久删除该表单【${it.form_name}】, 是否继续?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      _formDelete(it.form_id);
    })
    .catch(() => {});
};

const _formDelete = async (id) => {
  const ret = await api.form.disableForm(id);

  if (ret && ret.form_id) {
    emptyData();
    init();

    if (appForms.value && appForms.value.refresh) {
      appForms.value.refresh();
    }
  }
};

const handleFormShowEdit = () => {
  const name = _.get(currentData.value, 'form_name');
  formInfo.value = currentData.value;
  // showFormCreate.value = true;
  // formWinName.value = `表【${name}】`;

  $WinFormCreate(
    {
      formInfo: formInfo.value,
      isShowForm: true,
      onCancel: () => {
        handleCloseFormWin();
      }
    },
    {
      title: `表【${name}】`
    }
  );
};

const handleShowCopy = () => {
  const copy = _.cloneDeep(currentData.value);
  const origName = _.get(currentData.value, 'form_name');
  let code = `${copy.form_code}${$utils.getNanoid()}`;

  if (code.length > 32) {
    code = code.substr(code.length - 20);
  }

  copy.form_name = `${copy.form_name}_副本`;
  copy.form_code = code;
  copyForm.value = copy;
  isShowCopy.value = true;
  copyWinName.value = `复制表单【${origName}】`;
};

const formCopy = async () => {
  const ret = await api.form.copyForm({
    orig_form_id: copyForm.value.form_id,
    form_name: copyForm.value.form_name,
    form_code: copyForm.value.form_code
  });

  if (ret) {
    isShowCopy.value = false;
    $jui.toast('恭喜您，表单复制成功');
  }
};

const handleFormCacheClean = async () => {
  if (!currentData.value || !currentData.value.form_id) return;
  const ret = await api.form.clearCache(currentData.value.form_id);

  if (ret) {
    $jui.toast('操作成功！');
  }
};

const handleShowViews = () => {
  const name = _.get(currentData.value, 'form_name');
  showViewWin.value = true;
  formInfo.value = currentData.value;
  viewsWinName.value = `【${name}】的视图`;

  $WinFormViews(
    {
      formId: formInfo.value?.form_id,
      onCancel() {
        handleCloseViewWin();
      }
    },
    {
      title: `【${name}】的视图`
    }
  );
};

const handleCloseViewWin = () => {
  showViewWin.value = false;
  formInfo.value = null;
};

const handleShowActions = () => {
  const name = _.get(currentData.value, 'form_name');
  formInfo.value = currentData.value;
  showActionWin.value = true;
  actionWinName.value = `【${name}】所有功能按钮`;
};

const handleFormShowSetting = (stepActive = 'action') => {
  const name = _.get(currentData.value, 'form_name');
  formInfo.value = currentData.value;
  // showSettingCreate.value = true;
  settingWinName.value = `【${name}】高级设置`;
  // settingStepActive.value = stepActive;

  $WinFormSetting({
    stepActive: stepActive,
    formId: formInfo.value?.form_id,
    isView: props.isView,
    onCancel: () => {}
  });
};

const handleSelect = (it) => {
  emit('select', it);
};

const handleShowFlowEditWin = () => {
  flowForm.value = currentData.value;
  showFlowCreate.value = true;
};

const handleShowFlowAddWin = () => {
  flowForm.value = currentData.value;
  showFlowCreate.value = true;
};

const handleCloseFlowWin = async () => {
  showFlowCreate.value = false;

  const formId = _.get(currentData.value, 'form_id');

  if (formId) {
    const form = await getFormInfo(formId);
    if (form && currentData.value && currentData.value.form_id === form.form_id) {
      _.assign(currentData.value, form);
    }
  }
};

const handleCloseSettingWin = () => {
  showSettingCreate.value = false;
};

const handleCloseFormWin = () => {
  showFormCreate.value = false;
  if (appForms.value && appForms.value.refresh) {
    appForms.value.refresh();
  }
};

const handleCloseCopyWin = () => {
  isShowCopy.value = false;
};

const handleChangeView = (formViewId) => {
  let viewLabel = '原始表单';

  if (currentData.value && currentData.value.views && formViewId > 0) {
    const view = _.find(currentData.value.views, { form_view_id: formViewId });

    if (view && view.view_name) {
      viewLabel = `视图：${view.view_name}`;
    }
  }

  viewLabel += `(${viewNum.value})`;

  currentFormViewLabel.value = viewLabel;
  currentFormViewId.value = formViewId;
};

const refreshMain = () => {
  const currentDataTemp = currentData.value;
  currentData.value = null;
  setTimeout(() => {
    if (!currentData.value) currentData.value = currentDataTemp;
  }, 0);
};

const viewNum = computed(() => {
  return (currentData.value && currentData.value.views && currentData.value.views.length) || 0;
});

const currentFormTemplateLabel = computed(() => {
  let tempNum = 0;

  if (currentData.value && currentData.value.templateCount) {
    tempNum = currentData.value.templateCount;
  }

  return `打印模板(${tempNum})`;
});

const currentFormMsgtplLabel = computed(() => {
  let msgNum = 0;

  if (currentData.value && currentData.value.msgTplCount) {
    msgNum = currentData.value.msgTplCount;
  }

  return `消息模板(${msgNum})`;
});

const currentFormSyncNum = computed(() => {
  let syncCount = 0;

  if (currentData.value && currentData.value.syncCount) {
    syncCount = currentData.value.syncCount;
  }
  return syncCount;
});

const currentFormBtnNum = computed(() => {
  let btnCount = 0;

  if (currentData.value && currentData.value.btnCount) {
    btnCount = currentData.value.btnCount;
  }
  return btnCount;
});

const appForms = ref(null);

onMounted(() => {
  init();
});

watch(
  () => currentData.value?.form_id,
  () => {
    currentFormViewId.value = -1;

    let viewLabel = '原始表单';

    viewLabel += `(${viewNum.value})`;
    currentFormViewLabel.value = viewLabel;
  }
);
</script>
